import React from 'react';
import PropTypes from 'prop-types';
import './index.scss';

class LoadingMore extends React.Component {
  constructor(props) {
    super(props);
    this.state = {

    }
    this.handelScroll = this.handelScroll.bind(this);
  }
  componentDidMount() {
    // 监听滚动条
    if (this.props.hasMore) {
      window.addEventListener('scroll', this.handelScroll)
    }
  }
  componentWillUnmount() {
    // 取消监听
    window.removeEventListener('scroll', this.handelScroll)
  }
  // 滚动事件
  handelScroll() {
    // 设置缓冲时间
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
    }
    const { wrapper } = this.refs;
    this.timeoutId = setTimeout(() => {
      // 元素距离浏览器顶部的距离
      const { top } = wrapper.getBoundingClientRect();
      // 浏览器窗口的高度
      const windowHeight = window.screen.height;
      // 元素距离顶窗口顶部的距离小于窗口的高度&&hasMore=ture，触发加载事件，
      if (top < windowHeight && this.props.hasMore) {
        this.props.getMore.bind(this)
      }
    }, 50)
  }
  render() {
    return (
      <div className="loading-more" ref="wrapper">
        {this.props.isLoading ?
          <div className="loading">
            加载中...
          </div>
          :
          this.props.hasMore ?
            <div className="more" onClick={this.props.hasMore ? this.props.getMore : null}>
              点击加载更多...
            </div>
            :
            <div className="no-more">
              没有更多了...
            </div>
        }
      </div>
    )
  }
}
export default LoadingMore;
LoadingMore.propTypes = {
  hasMore: PropTypes.bool,
  getMore: PropTypes.func,
  isLoading: PropTypes.bool,
}
